<template>
  <div class="practice-management-container">
    <!-- 主页面 -->
    <div class="header">
      <h2>实践活动管理</h2>
      <div class="display-controls">
        <el-radio-group v-model="displayMode" size="small">
          <el-radio-button label="card">
            <el-icon><Grid /></el-icon> 卡片
          </el-radio-button>
          <el-radio-button label="list">
            <el-icon><List /></el-icon> 列表
          </el-radio-button>
        </el-radio-group>
        <el-button type="primary" @click="showCreatePracticeDialog" class="create-btn">
          <el-icon><Plus /></el-icon> 创建实践活动
        </el-button>
      </div>
    </div>

    <!-- 卡片展示模式 -->
    <div v-if="displayMode === 'card'" class="practice-list">
      <el-card 
        v-for="practice in practices" 
        :key="practice.id" 
        class="practice-card"
        shadow="hover"
      >
        <div class="practice-header">
          <h3 class="practice-title">{{ practice.praName }}</h3>
          <div class="practice-status">
            <el-tag :type="getStatusTagType(practice.status)" size="small">
              {{ getStatusText(practice.status) }}
            </el-tag>
            <el-tag 
              v-if="practice.endTime" 
              :type="getCountdownTagType(practice)" 
              size="small"
              style="margin-left: 8px"
            >
              {{ getCountdownText(practice) }}
            </el-tag>
          </div>
        </div>
        
        <div class="practice-info">
          <p><span class="info-label">关联课程:</span> {{ practice.courseName }}</p>
          <p><span class="info-label">实践地点:</span> {{ practice.praSite }}</p>
          <p><span class="info-label">开始时间:</span> {{ formatDateTime(practice.startTime) }}</p>
          <p><span class="info-label">结束时间:</span> {{ practice.endTime ? formatDateTime(practice.endTime) : '未设置' }}</p>
          <p><span class="info-label">参与学生:</span> {{ practice.studentCount }}人</p>
        </div>
        
        <div class="practice-actions">
          <el-button-group class="action-group">
            <el-tooltip content="查看详情" placement="top">
              <el-button size="small" @click.stop="showPracticeDetail(practice)" circle>
                <el-icon><View /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
              <el-button size="small" type="primary" @click.stop="showEditPracticeDialog(practice)" circle>
                <el-icon><Edit /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button size="small" type="danger" @click.stop="confirmDeletePractice(practice.id)" circle>
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="管理学生" placement="top">
              <el-button size="small" type="info" @click.stop="showManageStudentsDialog(practice)" circle>
                <el-icon><User /></el-icon>
              </el-button>
            </el-tooltip>
          </el-button-group>
          
          <el-button 
            size="small" 
            type="success" 
            @click.stop="startPractice(practice)"
            v-if="practice.status === 0"
            class="start-practice-btn"
          >
            <el-icon><VideoPlay /></el-icon> 开始实践
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 列表展示模式 -->
    <div v-else class="practice-list-table">
      <el-table :data="practices" border style="width: 100%" v-loading="loading">
        <el-table-column prop="praName" label="实践名称" width="180" sortable></el-table-column>
        <el-table-column prop="courseName" label="关联课程" width="120"></el-table-column>
        <el-table-column prop="praSite" label="实践地点" width="120"></el-table-column>
        <el-table-column label="开始时间" width="150" sortable>
          <template #default="{row}">{{ formatDateTime(row.startTime) }}</template>
        </el-table-column>
        <el-table-column label="结束时间" width="150">
          <template #default="{row}">{{ row.endTime ? formatDateTime(row.endTime) : '未设置' }}</template>
        </el-table-column>
        <el-table-column label="参与学生" width="100">
          <template #default="{row}">{{ row.studentCount }}人</template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="{row}">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{row}">
            <el-button-group>
              <el-tooltip content="查看详情" placement="top">
                <el-button size="small" @click="showPracticeDetail(row)" circle>
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="编辑" placement="top">
                <el-button size="small" type="primary" @click="showEditPracticeDialog(row)" circle>
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button size="small" type="danger" @click="confirmDeletePractice(row.id)" circle>
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="管理学生" placement="top">
                <el-button size="small" type="info" @click="showManageStudentsDialog(row)" circle>
                  <el-icon><User /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="开始实践" placement="top" v-if="row.status === 0">
                <el-button size="small" type="success" @click="startPractice(row)" circle>
                  <el-icon><VideoPlay /></el-icon>
                </el-button>
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 创建实践活动对话框 -->
    <el-dialog v-model="createDialogVisible" title="创建实践活动" width="50%">
      <el-form :model="createForm" label-width="100px" :rules="createRules" ref="createFormRef">
        <el-form-item label="实践名称" prop="praName">
          <el-input v-model="createForm.praName" placeholder="请输入实践名称" />
        </el-form-item>
        <el-form-item label="关联课程" prop="couId">
          <el-select 
            v-model="createForm.couId" 
            placeholder="请选择关联课程" 
            style="width: 100%"
            filterable
            clearable
          >
            <el-option
              v-for="course in teacherCourses"
              :key="course.id"
              :value="course.id"
            >
              <span style="float: left">{{ course.id }}</span>
              <span style="float: right; color: #8492a6">{{ course.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实践地点" prop="praSite">
          <el-input v-model="createForm.praSite" placeholder="请输入实践地点" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="createForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="createForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="实践内容" prop="praMain">
          <el-input
            v-model="createForm.praMain"
            type="textarea"
            :rows="4"
            placeholder="请输入实践内容"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="createForm.description"
            type="textarea"
            :rows="2"
            placeholder="请输入描述信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCreateForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑实践活动对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑实践活动" width="50%">
      <el-form :model="editForm" label-width="100px" :rules="editRules" ref="editFormRef">
        <el-form-item label="实践名称" prop="praName">
          <el-input v-model="editForm.praName" placeholder="请输入实践名称" />
        </el-form-item>
        <el-form-item label="实践地点" prop="praSite">
          <el-input v-model="editForm.praSite" placeholder="请输入实践地点" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="editForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
            disabled
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="editForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="实践内容" prop="praMain">
          <el-input
            v-model="editForm.praMain"
            type="textarea"
            :rows="4"
            placeholder="请输入实践内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 实践活动详情对话框 -->
    <el-dialog v-model="detailDialogVisible" :title="currentPractice.praName" width="60%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="关联课程">{{ currentPractice.courseName }}</el-descriptions-item>
        <el-descriptions-item label="实践地点">{{ currentPractice.praSite }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ formatDateTime(currentPractice.startTime) }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ currentPractice.endTime ? formatDateTime(currentPractice.endTime) : '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(currentPractice.status)" size="small">
            {{ getStatusText(currentPractice.status) }}
          </el-tag>
          <el-tag v-if="currentPractice.endTime" :type="getCountdownTagType(currentPractice)" size="small" style="margin-left: 8px">
            {{ getCountdownText(currentPractice) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="参与学生">{{ currentPractice.studentCount }}人</el-descriptions-item>
        <el-descriptions-item label="实践内容" :span="2">
          <div class="practice-content">{{ currentPractice.praMain }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">
          <div class="practice-description">{{ currentPractice.description || '无' }}</div>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 管理学生对话框 -->
    <el-dialog v-model="studentDialogVisible" :title="`管理学生 - ${currentPractice.praName}`" width="70%">
      <div class="student-management">
        <div class="search-bar">
          <el-input
            v-model="studentSearchKeyword"
            placeholder="搜索学生"
            clearable
            style="width: 300px"
            @keyup.enter="searchStudents"
          >
            <template #append>
              <el-button @click="searchStudents">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
        
        <el-table :data="filteredStudents" style="width: 100%" height="400" v-loading="loading">
          <el-table-column prop="id" label="学号" width="180" sortable></el-table-column>
          <el-table-column prop="stuName" label="姓名" width="180"></el-table-column>
          <el-table-column label="状态" width="120">
            <template #default="{row}">
              <el-tag :type="studentStatus[row.id] ? 'success' : 'info'" size="small">
                {{ studentStatus[row.id] ? '已加入' : '未加入' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{row}">
              <el-button
                v-if="!studentStatus[row.id]"
                type="primary"
                size="small"
                @click="addStudentToPractice(row.id)"
                :icon="Plus"
              >
                添加
              </el-button>
              <el-button
                v-else
                type="danger"
                size="small"
                @click="removeStudentFromPractice(row.id)"
                :icon="Delete"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watchEffect } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Search, 
  Grid, 
  List, 
  View, 
  Edit, 
  Delete, 
  User, 
  VideoPlay 
} from '@element-plus/icons-vue'
import axios from 'axios'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()
const teacherId = ref(null)
const loading = ref(false)
const displayMode = ref('card') // 默认卡片模式

// 实践活动数据
const practices = ref([])
const currentPractice = ref({
  id: null,
  praName: '',
  courseName: '',
  praSite: '',
  praMain: '',
  startTime: '',
  endTime: null,
  status: 0,
  studentCount: 0,
  description: ''
})

// 教师课程数据
const teacherCourses = ref([])

// 学生数据
const allStudents = ref([])
const practiceStudents = ref([])
const studentSearchKeyword = ref('')
const studentStatus = ref({}) // 学生状态映射

// 对话框控制
const createDialogVisible = ref(false)
const editDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const studentDialogVisible = ref(false)

// 表单数据
const createForm = ref({
  praName: '',
  couId: null,
  praSite: '',
  praMain: '',
  startTime: '',
  endTime: null,
  description: ''
})

const editForm = ref({
  id: null,
  praName: '',
  praSite: '',
  praMain: '',
  startTime: '',
  endTime: null
})

// 表单引用
const createFormRef = ref(null)
const editFormRef = ref(null)

// 表单验证规则
const createRules = {
  praName: [{ required: true, message: '请输入实践名称', trigger: 'blur' }],
  couId: [{ required: true, message: '请选择关联课程', trigger: 'change' }],
  praSite: [{ required: true, message: '请输入实践地点', trigger: 'blur' }],
  praMain: [{ required: true, message: '请输入实践内容', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }]
}

const editRules = {
  praName: [{ required: true, message: '请输入实践名称', trigger: 'blur' }],
  praSite: [{ required: true, message: '请输入实践地点', trigger: 'blur' }],
  praMain: [{ required: true, message: '请输入实践内容', trigger: 'blur' }]
}

// 获取教师ID
const fetchTeacherId = async () => {
  try {
    if (!authStore.userId) {
      throw new Error('用户ID不存在')
    }

    const response = await axios.get(`/spoc/teacher/getTeacherByUid/${authStore.userId}`)
    const teacherData = response.data
    
    if (!teacherData) {
      throw new Error('教师信息不存在')
    }
    
    if (!teacherData.id) {
      throw new Error('教师ID不存在')
    }
    
    teacherId.value = teacherData.id
    return teacherId.value
  } catch (error) {
    ElMessage.error('获取教师信息失败: ' + error.message)
    return null
  }
}

// 获取教师的所有实践活动
const fetchPractices = async () => {
  try {
    loading.value = true
    if (!teacherId.value) {
      await fetchTeacherId()
    }
    const response = await axios.get(`/api/practices/teacher/${teacherId.value}`)
    practices.value = response.data
  } catch (error) {
    ElMessage.error('获取实践活动列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 获取教师的课程
const fetchTeacherCourses = async () => {
  try {
    if (!teacherId.value) {
      await fetchTeacherId()
    }
    const response = await axios.get(`/spoc/vod/course/teacherCourseList/${teacherId.value}`)
    teacherCourses.value = response.data.map(course => ({
      id: course.id,
      name: course.courseName || '未命名课程'
    }))
  } catch (error) {
    ElMessage.error('获取课程列表失败: ' + error.message)
  }
}

// 获取所有学生
const fetchAllStudents = async () => {
  try {
    const response = await axios.get('/spoc/api/students')
    allStudents.value = response.data
    return allStudents.value
  } catch (error) {
    ElMessage.error('获取学生列表失败: ' + error.message)
    return []
  }
}

// 获取实践活动关联的学生
const fetchPracticeStudents = async (practiceId) => {
  try {
    const response = await axios.get(`/api/practices/${practiceId}/students`)
    practiceStudents.value = response.data
    return practiceStudents.value
  } catch (error) {
    ElMessage.error('获取参与学生失败: ' + error.message)
    return []
  }
}

// 检查学生是否在实践活动中
const checkStudentsInPractice = async (practiceId, studentIds) => {
  try {
    const practiceStudents = await fetchPracticeStudents(practiceId)
    const statusMap = {}
    studentIds.forEach(studentId => {
      statusMap[studentId] = practiceStudents.some(student => student.id === studentId)
    })
    return statusMap
  } catch (error) {
    ElMessage.error('检查学生状态失败: ' + error.message)
    return {}
  }
}

// 更新学生状态映射
const updateStudentStatus = async () => {
  if (!allStudents.value.length) {
    await fetchAllStudents()
  }
  
  const studentIds = allStudents.value.map(student => student.id)
  studentStatus.value = await checkStudentsInPractice(currentPractice.value.id, studentIds)
}

// 创建实践活动
const submitCreateForm = async () => {
  try {
    await createFormRef.value.validate()
    
    if (!teacherId.value) {
      await fetchTeacherId()
    }
    
    const requestData = {
      couId: createForm.value.couId,
      praName: createForm.value.praName,
      praSite: createForm.value.praSite,
      praMain: createForm.value.praMain,
      description: createForm.value.description,
      startTime: createForm.value.startTime.replace(' ', 'T'),
      endTime: createForm.value.endTime.replace(' ', 'T')
    }

    const response = await axios.post(`/api/practices?teaId=${teacherId.value}`, requestData)
    
    if (response.status === 201) {
      ElMessage.success('创建成功')
      createDialogVisible.value = false
      fetchPractices()
    } else {
      ElMessage.error('创建失败: ' + response.data.message)
    }
  } catch (error) {
    if (error.name !== 'ValidationError') {
      ElMessage.error('创建失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

// 更新实践活动
const submitEditForm = async () => {
  try {
    await editFormRef.value.validate()
    
    const response = await axios.put(`/api/practices/${editForm.value.id}`, editForm.value)
    ElMessage.success('更新成功')
    editDialogVisible.value = false
    fetchPractices()
  } catch (error) {
    if (error.name !== 'ValidationError') {
      ElMessage.error('更新失败: ' + error.message)
    }
  }
}

// 删除实践活动
const confirmDeletePractice = (id) => {
  ElMessageBox.confirm('确定要删除这个实践活动吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await axios.delete(`/api/practices/${id}`)
      ElMessage.success('删除成功')
      fetchPractices()
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  }).catch(() => {})
}

// 添加学生到实践活动
const addStudentToPractice = async (studentId) => {
  try {
    await axios.post(`/api/practices/${currentPractice.value.id}/students`, [studentId])
    ElMessage.success('添加成功')
    await fetchPracticeStudents(currentPractice.value.id)
    await updateStudentStatus()
  } catch (error) {
    ElMessage.error('添加失败: ' + error.message)
  }
}

// 从实践活动移除学生
const removeStudentFromPractice = async (studentId) => {
  try {
    await axios.delete(`/api/practices/${currentPractice.value.id}/students/${studentId}`)
    ElMessage.success('移除成功')
    await fetchPracticeStudents(currentPractice.value.id)
    await updateStudentStatus()
  } catch (error) {
    ElMessage.error('移除失败: ' + error.message)
  }
}

// 搜索学生
const searchStudents = () => {
  fetchAllStudents()
}

// 过滤学生列表
const filteredStudents = computed(() => {
  if (!studentSearchKeyword.value) return allStudents.value
  
  return allStudents.value.filter(student => 
    (student.name && student.name.includes(studentSearchKeyword.value)) || 
    (student.username && student.username.includes(studentSearchKeyword.value))
  )
})

// 显示创建实践活动对话框
const showCreatePracticeDialog = () => {
  createForm.value = {
    praName: '',
    couId: null,
    praSite: '',
    praMain: '',
    startTime: '',
    endTime: null,
    description: ''
  }
  createDialogVisible.value = true
}

// 显示编辑实践活动对话框
const showEditPracticeDialog = (practice) => {
  editForm.value = {
    id: practice.id,
    praName: practice.praName,
    praSite: practice.praSite,
    praMain: practice.praMain,
    startTime: practice.startTime,
    endTime: practice.endTime
  }
  editDialogVisible.value = true
}

// 显示实践活动详情对话框
const showPracticeDetail = (practice) => {
  currentPractice.value = { ...practice }
  detailDialogVisible.value = true
}

// 显示管理学生对话框
const showManageStudentsDialog = async (practice) => {
  try {
    currentPractice.value = practice
    const [students] = await Promise.all([fetchAllStudents()])
    await updateStudentStatus()
    studentDialogVisible.value = true
  } catch (error) {
    ElMessage.error('打开管理对话框失败: ' + error.message)
  }
}

// 开始实践活动 - 仅前端处理
// 修改后的startPractice方法
const startPractice = async (practice) => {
  try {
    await ElMessageBox.confirm('确定要开始这个实践活动吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 更新卡片视图中的状态
    const cardIndex = practices.value.findIndex(p => p.id === practice.id)
    if (cardIndex !== -1) {
      practices.value[cardIndex].status = 1
    }
    
    // 确保列表视图也能获取到更新后的状态
    // 因为el-table使用的是practices.value数据，所以不需要额外处理
    
    ElMessage.success('实践活动已开始')
    
    // 如果需要后端同步，可以在这里添加API调用
    // await axios.patch(`/api/practices/${practice.id}/status`, { status: 1 })
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('开始实践失败: ' + error.message)
    }
  }
}

// 计算剩余天数
const calculateDaysRemaining = (endTime) => {
  if (!endTime) return null
  const end = new Date(endTime)
  const now = new Date()
  const diffTime = end - now
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
}

// 获取倒计时标签类型
const getCountdownTagType = (practice) => {
  if (!practice.endTime) return 'info'
  const days = calculateDaysRemaining(practice.endTime)
  if (days <= 0) return 'danger'
  if (days <= 3) return 'warning'
  return 'success'
}

// 获取倒计时文本
const getCountdownText = (practice) => {
  if (!practice.endTime) return '无截止时间'
  const days = calculateDaysRemaining(practice.endTime)
  if (days <= 0) return '已结束'
  return `剩余${days}天`
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 0: return 'info' // 未开始
    case 1: return 'primary' // 进行中
    case 2: return 'success' // 已完成
    case 3: return 'danger' // 已取消
    default: return ''
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '未开始'
    case 1: return '进行中'
    case 2: return '已完成'
    case 3: return '已取消'
    default: return '未知状态'
  }
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 监听学生数据变化
watchEffect(() => {
  if (allStudents.value.length > 0 && studentDialogVisible.value) {
    updateStudentStatus()
  }
})

// 初始化数据
onMounted(async () => {
  await fetchTeacherId()
  fetchPractices()
  fetchTeacherCourses()
})
</script>

<style scoped>
.practice-management-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 20px;
}

.display-controls {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.create-btn {
  margin-left: auto;
}

.practice-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 10px;
}

.practice-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
  height: 100%;
  width: 280px;
  display: flex;
  flex-direction: column;
}

.practice-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1);
}

.practice-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.practice-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.practice-status {
  display: flex;
  align-items: center;
}

.practice-info {
  margin-bottom: 15px;
  flex: 1;
}

.practice-info p {
  margin: 6px 0;
  font-size: 14px;
  color: #666;
  display: flex;
}

.info-label {
  font-weight: 500;
  color: #333;
  min-width: 80px;
  display: inline-block;
}

.practice-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.action-group {
  display: flex;
  gap: 12px;
}

.start-practice-btn {
  margin-left: auto;
}

.practice-list-table {
  margin-top: 20px;
}

.student-management {
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.practice-content,
.practice-description {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .display-controls {
    width: 100%;
    justify-content: space-between;
  }
  
  .create-btn {
    margin-left: 0;
    width: 100%;
    margin-top: 10px;
  }
  
  .practice-list {
    grid-template-columns: 1fr;
  }
  
  .practice-actions {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .start-practice-btn {
    width: 100%;
    margin-top: 8px;
  }
}
</style>